package routes

import (
    "shiyan4/models"
    "net/http"

    "github.com/gin-gonic/gin"
    "gorm.io/driver/mysql"
    "gorm.io/gorm"
)

func SetupRouter(r *gin.Engine) {
    // 初始化数据库连接
    dsn := "root:123456@tcp(127.0.0.1:3306)/experiment_db?charset=utf8mb4&parseTime=True&loc=Local"
    db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
    if err != nil {
        panic("failed to connect database")
    }
    // 自动迁移表结构
    db.AutoMigrate(&models.User{})

    // GET请求控制器函数
    r.GET("/get", func(c *gin.Context) {
        var user models.User
        db.First(&user)
        c.HTML(http.StatusOK, "index.html", gin.H{
            "message": "GET请求成功",
            "data":    user,
        })
    })

    // POST请求控制器函数
    r.POST("/post", func(c *gin.Context) {
        var newUser models.User
        if err := c.ShouldBindJSON(&newUser); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
            return
        }
        db.Create(&newUser)
        c.JSON(http.StatusOK, gin.H{"message": "POST请求成功，数据已保存"})
    })
}